// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import HardModeGame from "./HardModeGame";
import Hp from "./Hp";

const {ccclass, property} = cc._decorator;

@ccclass
export default class HardModePlayer extends cc.Component {

    static inst: HardModePlayer = null;

    // 爆炸特效
    @property(cc.SpriteFrame)
    explodeEffect: cc.SpriteFrame = null;
    
    @property(cc.AudioClip)
    audio: cc.AudioClip = null;

    @property
    minX: number = 0;

    @property
    maxX: number = 0;

    healthPoint: number = 0;

    // LIFE-CYCLE CALLBACKS:

    onLoad () {

        HardModePlayer.inst = this;

        this.healthPoint = 50;

        this.node.on('touchmove', this.onTouchMove, this); 
    }

    start () {

        //创建定时器
        //this.schedule(this.onTimer, 0.3, cc.macro.REPEAT_FOREVER, 0.01);
    }

    // 发射子弹
    shoot() {

        if(HardModeGame.inst.playing == false) return;

        // 动态创建子弹
        let bulletNode = HardModeGame.inst.createBullet();

        bulletNode.setPosition(this.node.x, this.node.y + this.node.height);
        this.node.parent.addChild(bulletNode); //挂在Canvas节点下面
    }

    onTouchMove(e: cc.Event.EventTouch) {

        let delta = e.getDelta();

        //范围检测
        if(this.node.x < this.minX) this.node.x = this.minX;
        if(this.node.x > this.maxX) this.node.x = this.maxX;

        if(this.node.x <= this.maxX && this.node.x >= this.minX) {
            
            this.node.x += delta.x;
        }       
    }

    // update (dt) {}

    onCollisionEnter(other: cc.Collider, self: cc.Collider) {

        if(other.node.name == '敌机子弹') {

            this.healthPoint -= 1;

            cc.log("生命值为" + this.healthPoint);

            Hp.i.updateHp(this.healthPoint);

            if(this.healthPoint <= 0) {

                cc.log("生命值为0, 玩家死亡");
                HardModeGame.inst.hardGameOver();
            }
        }
        else if (other.node.name == '敌机') {

            cc.log('敌机与玩家发生撞机, 玩家死亡');

            this.healthPoint = 0;

            Hp.i.updateHp(this.healthPoint);

            HardModeGame.inst.hardGameOver();
        }
    }
}
